const fs = require('fs-extra');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const { spawn } = require('child_process');

const { version } = JSON.parse(fs.readFileSync('./package.json', 'utf8'));

module.exports = ({ onGetWebpackConfig }) => {
  onGetWebpackConfig((config) => {
    config.resolve.plugin('tsconfigpaths').use(TsconfigPathsPlugin, [
      {configFile: './tsconfig.json'},
    ]);
    config.merge({node: {fs: 'empty'}});

    config.plugin('index').use(HtmlWebpackPlugin, [{
      inject: false,
      minify: false,
      templateParameters: { version },
      template: require.resolve('./public/index.html'),
      filename: 'index.html',
    }]);
    
    config.plugin('preview').use(HtmlWebpackPlugin, [{
      inject: false,
      templateParameters: {},
      template: require.resolve('./public/preview.html'),
      filename: 'preview.html',
    }]);
    
    config.plugin('home').use(HtmlWebpackPlugin, [{
      inject: false,
      templateParameters: {},
      template: require.resolve('./public/home.html'),
      filename: 'home.html',
    }]);

    config.plugin('creator').use(HtmlWebpackPlugin, [{
      inject: false,
      minify: false,
      templateParameters: { version },
      template: require.resolve('./public/creator.ejs'),
      filename: 'creator.html',
    }]);

    config.plugins.delete('hot');
    config.devServer.hot(false);
    config.module // fixes https://github.com/graphql/graphql-js/issues/1272
      .rule('mjs$')
      .test(/\.mjs$/)
      .include
      .add(/node_modules/)
      .end()
      .type('javascript/auto');
  });

  // 开启服务器
  const assetServerChild = spawn('node', ['./asset-server.js'], {
    cwd: __dirname,
  });
  assetServerChild.stdout.pipe(process.stdout);

  // 开启组件编译
  // console.log(process.platform);
  // console.log(process.arch);
  // process.exit(0);
  const isWindows = process.platform === 'win32';
  console.log('-- 执行组件编译程序 --');
  const child = spawn(isWindows ? 'npm.cmd': 'npm', ['run', 'wbuild'], {
    cwd: path.resolve(__dirname, 'components'),
  });
  child.stdout.pipe(process.stdout);
  
  // await spawn(process.platform === 'win32' ? 'npm.cmd': 'npm', ['run', 'wbuild'], { cwd: 、./${name}' })

};
